//
//  JiaoShiPaiMingViewController.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/12/8.
//  Copyright © 2015年 中良 赵. All rights reserved.
//

#import "JiaoShiPaiMingViewController.h"
#import "NewCell.h"
#import"OrderCell.h"
#import "JSPMTableViewCell.h"
#import "RankCell.h"
#import "RankModel.h"
#import "InfoViewController.h"

@interface JiaoShiPaiMingViewController ()
{
    UIView *_chooseView;
    UITableView *_tableView;
    NSMutableDictionary *_checkDictionary;
    MBProgressHUD *_HUD;
    
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;
    NSMutableArray *rankArr;
    
//    MainCourseModel *_mainCourseModel;
    NSString *_lat;
    NSString *_lng;
    NSMutableArray *_dataArray;
    
    NSInteger _index;
        int pageSize ;
    
    RankModel *rankModel;

}
@end

@implementation JiaoShiPaiMingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self creatNavigationBarWithImage:nil title:@"抢单"];
    _index=0;
    pageSize=20;
    [self creatChooseView];
    [self creatTableView];
    [_tableView.mj_header beginRefreshing];
}
- (void)creatThirdHttpRequest
{
    NSDictionary *param = @{
//                            @"member_Id":_memberModel.member_Id,
                            @"pageIndex":[NSString stringWithFormat:@"%ld",(long)_index],
                            @"pageSize":@"20",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(RANK) params:param complete:^(BOOL successed, NSDictionary *result) {
        NSLog(@"result===%@",result);
        if (successed) {
            [RankModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"RankData",
                         };
            }];
            rankModel = [[RankModel alloc] init];
            rankModel = [RankModel objectWithKeyValues:result];
            if (rankArr.count==0) {
                    rankArr = [[NSMutableArray alloc] init];
                    rankArr=[NSMutableArray arrayWithArray:rankModel.data];

            }else{
                [rankArr addObjectsFromArray:rankModel.data];
            }
            NSLog(@"%@",rankArr);
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
        else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)headerRefreshing
{
    _index = 0;
    [self creatThirdHttpRequest];
}

- (void)footerRefreshing
{
    if (_dataArray.count%10 == 0) {
        _index ++;
        [self creatThirdHttpRequest];
    }else{
        [_tableView.mj_footer endRefreshing];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self loadUserInfo];
    UIButton *button = (UIButton *)[self.view viewWithTag:105];
    [self chooseClick:button];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showHUD
{
    _HUD = [[MBProgressHUD alloc] initWithView:self.view];
}

- (void)loadUserInfo
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    _memberModel = userInfo.memberModel;
    _teacherModel = userInfo.teacherModel;
    _lat = userInfo.lat;
    _lng = userInfo.lng;
}


- (void)creatChooseView
{
    _chooseView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ECSCREEN_W, 40)];
    _chooseView.backgroundColor = ECCOLOR(255, 255, 255, 1);
    [self.view addSubview:_chooseView];
    
    
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.tag = 105;
    newButton.frame = CGRectMake(0, 0, ECSCREEN_W/2, 40);
    [newButton setTitle:@"综合排名" forState:UIControlStateNormal];
    [newButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
    newButton.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [newButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
    newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 150, 0, 0);
    [newButton addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    [_chooseView addSubview:newButton];
    
    UIView *speraLine = [[UIView alloc] initWithFrame:CGRectMake(ECSCREEN_W/2, 5, 1, 30)];
    speraLine.backgroundColor = ECCOLOR(212, 50, 47, .3f);
    [_chooseView addSubview:speraLine];
    
    
    UIButton *orderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    orderButton.tag = 106;
    orderButton.frame = CGRectMake(ECSCREEN_W/2+1, 0, ECSCREEN_W/2, 40);
    [orderButton setTitle:@"主页浏览量" forState:UIControlStateNormal];
    [orderButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
    orderButton.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [orderButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
    orderButton.imageEdgeInsets = UIEdgeInsetsMake(0, 130, 0, 0);
    [orderButton addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    [_chooseView addSubview:orderButton];
}



- (void)chooseClick:(UIButton *)button
{
    UIButton *newButton = (UIButton *)[self.view viewWithTag:105];
    UIButton *orderButton = (UIButton *)[self.view viewWithTag:106];
    
    switch (button.tag) {
        case 105:
        {
            newButton.selected = YES;
            orderButton.selected = NO;
            [newButton setTitleColor:NAVC_COLOR forState:UIControlStateNormal];
            [orderButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
            [newButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
            [orderButton setImage:ECIMAGENAME(@"order_up.png") forState:UIControlStateNormal];
            if (_lat.length >0 &&_lng.length > 0) {
//                [self creatFirstHttpRequest];
            }
        }
            break;
        case 106:
        {
            newButton.selected = NO;
            orderButton.selected = YES;
            [newButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
            [orderButton setTitleColor:NAVC_COLOR forState:UIControlStateNormal];
            [newButton setImage:ECIMAGENAME(@"order_up.png") forState:UIControlStateNormal];
            [orderButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
            if (_lat.length >0 &&_lng.length > 0) {
//                [self creatSecondHttpRequest];
            }
        }
            break;
            
            
        default:
            break;
    }
}







- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 109, ECSCREEN_W, ECSCREEN_H - 109 ) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
}


#pragma mark - tableViewNumberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    return _dataArray.count;
    return rankArr.count;

}


#pragma mark - tableViewHeightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110.f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RankData *data=rankArr[indexPath.row];
    InfoViewController *vc=[[InfoViewController alloc]init];
    vc.memberId=data.member_Id;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - tableViewCellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIButton *button = (UIButton *)[self.view viewWithTag:105];
    if (button.selected) {
        static NSString *reuseIdentifier = @"JSPMTableViewCell";
        JSPMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
//            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"JSPMTableViewCell" owner:nil options:nil];
            cell=[[[NSBundle mainBundle] loadNibNamed:@"JSPMTableViewCell" owner:self options:nil] objectAtIndex:0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            for (NSObject *obj in arr) {
//                if ([obj isKindOfClass:[NewCell class]]) {
//                    cell = (NewCell *)obj;
//                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
//                        [cell setSeparatorInset:UIEdgeInsetsZero];
//                    }
//                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//                        [cell setLayoutMargins:UIEdgeInsetsZero];
//                    }
//                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//                    break;
//                }
//            }
        }
//        [cell setCellWithModel:_dataArray WithIndexPath:indexPath];
        RankData *data=rankArr[indexPath.row];
        cell.lblTeaName.text=data.name;
        cell.lblZone.text=data.city;
        cell.lblTeachAge.text=data.seniority;
        cell.lblPingFen.text=[NSString stringWithFormat:@"%@分",data.score];
        [cell.imgTeacherPhoto setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:data.imgUrl]] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            cell.imgTeacherPhoto.image=image;
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        }];
        cell.lblRenzheng.text=[NSString stringWithFormat:@"%@项认证",data.certificationCount];
        [cell.starView setImagesDeselected:@"star_gray.png" partlySelected:@"" fullSelected:@"star_orange.png" andDelegate:self];
        [cell.starView displayRating:data.score.intValue];
        
//        [cell setCellWithModel:nil WithIndexPath:indexPath];

        return cell;
        
    }else{
        static NSString *reuseIdentifier = @"orderCell";
        OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"OrderCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[OrderCell class]]) {
                    cell = (OrderCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    
                    [cell.checkButton addTarget:self action:@selector(checkButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                    
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        
        cell.checkButton.selected = [_checkDictionary[[NSString stringWithFormat:@"%ld",(long)indexPath.row]] boolValue];
        [cell setCellWithModel:_dataArray WithIndexPath:indexPath];
        return cell;
    }
}


- (void)checkButtonClick:(UIButton*)sender
{
    sender.selected = !sender.isSelected;
    
    UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    
    _checkDictionary[[NSString stringWithFormat:@"%ld",(long)indexPath.row]] = [NSNumber numberWithBool:sender.isSelected];
    
//    MainCourseData *data = _dataArray[indexPath.row];
//    [self changeOrderWithModel:data];
}

//- (void)changeOrderWithModel:(MainCourseData *)model
//{
//    NSDictionary *param = @{
//                            @"promulgator_Id":model.promulgator_Id,
//                            @"t_member_Id":_memberModel.member_Id,
//                            @"promulgator_mark":model.promulgator_mark,
//                            @"course_name":model.course_name,
//                            @"price":model.price,
//                            @"suits_the_crowd":model.suits_the_crowd,
//                            
//                            };
//}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
